package com.bizihang.common.security.app.code.impl;

import com.bizihang.common.security.core.code.ValidateCode;
import com.bizihang.common.security.core.code.ValidateCodeException;
import com.bizihang.common.security.core.code.ValidateCodeRepository;
import com.bizihang.common.security.core.code.ValidateCodeType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

/**
 * 基于redis的验证码存取器，避免由于没有session导致无法存取验证码的问题
 *
 * @author 毕子航 951755883@qq.com
 * @date 2018/10/24
 */
@Slf4j
@Component
public class RedisValidateCodeRepository implements ValidateCodeRepository {
	private final RedisTemplate<String, Object> redisTemplate;

	@Autowired
	public RedisValidateCodeRepository(RedisTemplate<String, Object> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	/**
	 * 保存验证码
	 *
	 * @param request the request
	 * @param code    the code
	 * @param type
	 */
	@Override
	public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType type) {
		String key = buildKey(request, type);
		redisTemplate.opsForValue().set(key, code, 3, TimeUnit.MINUTES);
		log.debug("请求的DeviceId:{},发送的{}验证码为:{}", key, code.getType(), code.getCode());
	}

	/**
	 * 获取验证码
	 *
	 * @param request the request
	 * @param type
	 * @return
	 */
	@Override
	public ValidateCode get(ServletWebRequest request, ValidateCodeType type) {
		Object value = redisTemplate.opsForValue().get(buildKey(request, type));
		if (value == null) {
			return null;
		}
		return (ValidateCode) value;
	}

	/**
	 * 删除验证码
	 *
	 * @param request the request
	 * @param type
	 */
	@Override
	public void remove(ServletWebRequest request, ValidateCodeType type) {
		redisTemplate.delete(buildKey(request, type));
	}

	private String buildKey(ServletWebRequest request, ValidateCodeType type) {
		String deviceId = request.getHeader("deviceId");
		if (StringUtils.isBlank(deviceId)) {
			throw new ValidateCodeException("请在请求头中携带deviceId参数");
		}
		return "code:" + type.toString().toLowerCase() + ":" + deviceId;
	}

}
